<?php

namespace app\admin\controller;

use think\Db;
use think\Request;
use think\Exception;//事务处理

class Price extends Auth
{
    public function __construct(Request $request){
        $this->getChildIDdata = [];
        parent::__construct($request);
        $this->data = $request->param();
        $this->user_id = session('userid') == null ? 1 : session('userid');
        $this->lang = isset($this->data['lang']) && $this->data['lang'] ? $this->data['lang'] : is_lang();
    }

    public function list()
    {   

        if(isset($this->data['page']) && $this->data['page']){
            $page = $this->data['page'];
        }else{
            $page = 1;
            
        }

        if(isset($this->data['limit']) && $this->data['limit']){
            $limit = $this->data['limit'];
        }else{
            $limit = 1000000000;
        }

        // 价格分类
        if(isset($this->data['request']) && $this->data['request'] == 'price_type'){
            $join = [
                        ['multi_lang mu','zu.mkey = mu.mkey',"LEFT"],
                        ['admin a','zu.create_id = a.id',"LEFT"]
                    ];
            // $price_type = getSearch('price_type','zu',['zu.*,mu.content,a.nickname'],['mu.lang'=>$this->lang],$join,'zu.drank asc');
            $price_type = Db::name('price_type')
                                ->alias('zu')
                                ->join($join)
                                ->field(['zu.*,mu.content,a.nickname'])
                                ->where(['mu.lang'=>$this->lang])
                                ->order('zu.drank asc')
                                ->page($page,$limit)
                                ->select();

            foreach ($price_type as $kprice_type => $vprice_type) {
                $price_type[$kprice_type]['time'] = getTimeDates($vprice_type['create_at'],$this->lang);
                $price_type[$kprice_type]['fixx'] = $vprice_type['fix'] == 1 ? "O" : '-';
                $price_type[$kprice_type]['ratee'] = $vprice_type['rate'] == 0 ? "-" : $vprice_type['rate'];
                $price_type[$kprice_type]['moqq'] = $vprice_type['moq'] == 0 ? "-" : $vprice_type['moq'];
                $price_type[$kprice_type]['discountt'] = $vprice_type['discount'] == 0 ? "-" : $vprice_type['discount'];
                $price_type[$kprice_type]['position'] = $this->processExplode($vprice_type['position_ids'],'position_');
                $price_type[$kprice_type]['department'] = $this->processExplode($vprice_type['department_ids'],'department_');
            }
            $pageSum = Db::name('price_type')->count();
            return json_encode(array('status'=>1,'data'=>['data'=>$price_type,'pageSum'=>$pageSum,'page'=>$page]));

        // 业务员折扣
        }else if(isset($this->data['request']) && $this->data['request'] == 'price_discount'){
            $position = $this->getPositions();
            // dump($position);die;
            // $price_discount = getDatas('price_discount',['*'],'1=1','id asc');
            $price_discount = Db::name('price_discount')->order('id desc')->page($page,$limit)->select();

            foreach ($price_discount as $k => $v) {
                
                $price_discount[$k]['time'] = getTimeDates($v['create_at'],$this->lang);
                $price_discount[$k]['nickname'] = getinfo($v['create_id'], 'admin')['nickname'];//编辑者
                foreach ($position as $k1 => $v1) {
                    if(array_search($v['position_id'], $v1) == 'id'){
                        $price_discount[$k]['level'] = $v1['level'];
                        $price_discount[$k]['langname'] = $v1['langname'];
                    }
                }
            }
            $pageSum = Db::name('price_discount')->count();
            return json_encode(array('status'=>1,'data'=>['data'=>$price_discount,'pageSum'=>$pageSum,'page'=>$page]));

        // 定价
        }else if(isset($this->data['request']) && $this->data['request'] == 'price'){
            $where = [];
            // 设置文本搜索条件
            if(isset($this->data['searchText']) && $this->data['searchText']) $where['zu.id|pm.content|zu.model'] = ['like',"%".$this->data['searchText'].'%'];
            // 设置产品类型条件
            if(isset($this->data['proCateId']) && $this->data['proCateId']) $where['pt.procat_id'] = $this->data['proCateId'];

            $priceData = model('Price')->getProPrice([],$this->lang,$where,$page,$limit);
            // dump($priceData);die;
            return json_encode(array('status'=>1,'data'=>$priceData));

        }else{
            return view('list');
        }
    }


    // 获取系统变量，以计算运费/CIF
    function getSysVariable()
    {
        $sysVariable = getDatas('sys_variable',['*'],'1=1','id asc');
        foreach ($sysVariable as $k => $v) {
            $res = Db::name('sys_variable_value')->where('variable_id',$v['id'])->order('create_at desc')->value('value');
            $sysVariableAndValue[$v['name']] = $sysVariable[$k];
            $sysVariableAndValue[$v['name']]['value'] = $res == null ? 0 : $res;

        }
        return $sysVariableAndValue;
    }


    function processExplode($data,$mkey)
    {

        $returnData = '';
        if($data != ''){
            $dataarr = explode(',', $data);
            foreach ($dataarr as $k => $v) {
                $returnData .= Db::name('multi_lang')->where(['mkey'=>$mkey.$v,'lang'=>$this->lang])->value('content').' / ';
            }
        }
        return rtrim($returnData,' / ');
    }

    // 添加价格分类添加
    public function  addPriceType(Request $request)
    {
        if(isset($this->data['request']) && $this->data['request'] == 'insert'){
            // dump($this->data);
            if(isset($this->data['code']) && $this->data['code'] && isset($this->data['name']) && $this->data['name']){
                // 判断价格分类是否已存在
                $has_name = hasData('multi_lang',['lang'=>$this->lang,'mkey'=>['like','%price_type_%'],'content'=>$this->data['name']]);
                if($has_name) return json_encode(array('status'=>2,'msg'=>$this->data['name'].' '.lang('already_exists')));
                //  判断价格分类code 是否已存在
                $has_code = hasData('price_type',['code'=>$this->data['code']]);
                if($has_code) return json_encode(array('status'=>2,'msg'=>$this->data['code'].' '.lang('already_exists')));

                $insertData['department_ids'] = $this->implodeStr($this->data['department']);
                $insertData['position_ids'] = $this->implodeStr($this->data['position']);
                $insertData['code'] = $this->data['code'];
                $insertData['rate'] = $this->data['rate'];
                $insertData['moq'] = $this->data['moq'];
                $insertData['discount'] = $this->data['discount'];
                $insertData['drank'] = $this->data['drank'];
                $insertData['create_id'] = $this->user_id;
                $insertData['create_at'] = time();
                // dump($insertData);die;
                // 是否需要重新排序
                if(hasData('price_type',['drank'=>$this->data['drank']])){
                    $is_drank = changeDrank(100,'price_type',$this->data['drank']);
                }

                Db::startTrans();
                $priceTypeId = insertData('price_type',$insertData);
                if($priceTypeId){
                    $res_u = updateData('price_type',['id'=>$priceTypeId],['mkey'=>'price_type_'.$priceTypeId]);
                    if($res_u){
                        $res_m = insertMuitl('price_type_'.$priceTypeId,$this->data['name']);
                        if($res_m){
                            Db::commit();
                            return json_encode(array('status'=>1,'msg'=>$this->data['name'].' '.lang('added_successfully')));
                        }else{
                            Db::rollback();
                            return json_encode(array('status'=>0,'msg'=>$this->data['name'].' '.lang('add_failed')));
                        }
                    }else{
                        Db::rollback();
                        return json_encode(array('status'=>0,'msg'=>$this->data['name'].' '.lang('add_failed')));
                    }
                }else{
                    Db::rollback();
                    return json_encode(array('status'=>0,'msg'=>$this->data['name'].' '.lang('add_failed')));
                } 
            }else{
                return json_encode(array('status'=>2,'msg'=>lang('improve_submission_data')));
            }
        }else{
            return view('addpricetype',['requestType'=>'add','title'=>'添加产品价格分类']);
        }
        
    }


    // function insertMuitl($mkey,$content){
    //     $langData = getLanguage();
    //     foreach ($langData as $k => $v) {
    //         $insertData['mkey'] = $mkey;
    //         $insertData['content'] = $content;
    //         $insertData['lang'] = $v['code'];
    //         $res = insertData('multi_lang',$insertData);
    //     }
    //     return $res;
    // }


    function implodeStr($data)
    {   
        $returnData = '';
        if(!empty($data)){
            foreach ($data as $k => $v) {
                if($v['ischecked'] == 'true'){
                    $returnData .= $v['id'].',';
                }
            }
        }
        return rtrim($returnData,',');
    }

    // 价格分类编辑
    public function priceTypeEdit()
    {
        if(isset($this->data['request']) && $this->data['request'] == 'edit'){
            if($this->data['id']){
                $detail = Db::name('price_type')->where('id',$this->data['id'])->find();
                $detail['olddrank'] = $detail['drank'];
                $detail['position_ids'] = explode(',', $detail['position_ids']);
                $detail['department_ids'] = explode(',', $detail['department_ids']);
                $detail['name'] = Db::name('multi_lang')->where(['mkey'=>'price_type_'.$this->data['id'],'lang'=>$this->lang])->value('content');
                // dump($position);
                return json_encode(array('status'=>1,'data'=>$detail));
            }else{
                return json_encode(array('status'=>2,'msg'=>'请求数据有误'));
            }
        }else if(isset($this->data['request']) && $this->data['request'] == 'update'){

            if(isset($this->data['code']) && $this->data['code'] && isset($this->data['name']) && $this->data['name']){
                // dump($this->data);die;
                // 判断价格分类是否已存在
                $has_name = hasData('multi_lang',['lang'=>$this->lang,'mkey'=>['like','%price_type_%'],'content'=>$this->data['name'],'mkey'=>['neq','price_type_'.$this->data['id']]]);
                if($has_name) return json_encode(array('status'=>2,'msg'=>$this->data['name'].' '.lang('already_exists')));
                //  判断价格分类code 是否已存在
                $has_code = hasData('price_type',['code'=>$this->data['code'],'id'=>['neq',$this->data['id']]]);
                if($has_code) return json_encode(array('status'=>2,'msg'=>$this->data['code'].' '.lang('already_exists')));

                $updateData['department_ids'] = $this->implodeStr($this->data['department']);
                $updateData['position_ids'] = $this->implodeStr($this->data['position']);
                $updateData['code'] = $this->data['code'];
                $updateData['rate'] = $this->data['rate'];
                $updateData['moq'] = $this->data['moq'];
                $updateData['discount'] = $this->data['discount'];
                $updateData['drank'] = $this->data['drank'];
                $updateData['update_id'] = $this->user_id;
                $updateData['update_at'] = time();
                // dump($insertData);die;


                // 是否需要从新排序
                if(hasData('price_type',['drank'=>$this->data['drank']])){
                    if($this->data['drank'] != $this->data['olddrank']){
                        $is_drank = changeDrank(100,'price_type',$this->data['drank'],$this->data['olddrank']);
                    }
                }

                Db::startTrans();
                    $res_u = updateData('price_type',['id'=>$this->data['id']],$updateData);
                    if($res_u){
                        $res_m = updateData('multi_lang',['mkey'=>'price_type_'.$this->data['id'],'lang'=>$this->lang],['content'=>$this->data['name']]);
                        if($res_m >= 0){
                            Db::commit();
                            return json_encode(array('status'=>1,'msg'=>$this->data['name'].' '.lang('edited_successfully')));
                        }else{
                            Db::rollback();
                            return json_encode(array('status'=>0,'msg'=>$this->data['name'].' '.lang('edit_failed')));
                        }
                    }else{
                        Db::rollback();
                        return json_encode(array('status'=>0,'msg'=>$this->data['name'].' '.lang('edit_failed')));
                    }
            }else{
                return json_encode(array('status'=>2,'msg'=>lang('improve_submission_data')));
            }
        }else{
            return view('addpricetype',['requestType'=>'edit','title'=>'编辑产品价格分类','id'=>$this->data['id']]);
        }
    }

    // 设置折扣价格添加
    public function  positionPrice()
    {   
        if(isset($this->data['request']) && $this->data['request'] == 'insert'){
        // dump($this->data);die;
            if(isset($this->data['range']) && $this->data['range'] && isset($this->data['qty']) && $this->data['qty'] && isset($this->data['amount']) && $this->data['amount']){
                if(!isset($this->data['position_id']) && !$this->data['position_id']) return json_encode(array('status'=>2,'msg'=>'请选择授权职务'));
                if(strlen($this->data['range']) > 2 ) return json_encode(array('status'=>2,'msg'=>'<范围> 数据过大'));
                // 判断职务是否已存在
                $has_position_id = hasData('price_discount',['position_id'=>$this->data['position_id']]);
                if($has_position_id) return json_encode(array('status'=>2,'msg'=>getValue('multi_lang',['mkey'=>'position_'.$this->data['position_id'],'lang'=>$this->lang],'content').' '.lang('already_exists')));

                $insertData['position_id'] = $this->data['position_id'];
                $insertData['range'] = $this->data['range'];
                $insertData['qty'] = $this->data['qty'];
                $insertData['amount'] = $this->data['amount'];
                $insertData['create_id'] = $this->user_id;
                $insertData['create_at'] = time();
                // dump($insertData);die;

                $priceTypeId = insertData('price_discount',$insertData);
                if($priceTypeId){
                    return json_encode(array('status'=>1,'msg'=>lang('added_successfully')));
                }else{
                    return json_encode(array('status'=>0,'msg'=>lang('add_failed')));
                } 
            }else{
                return json_encode(array('status'=>2,'msg'=>lang('improve_submission_data')));
            }
        }else{
            return view('positionprice',['requestType'=>'add','title'=>'职务价格折扣设置']);
        }
        
    }

    // 业务员折扣 编辑
    public function positionPriceEdit()
    {
        if(isset($this->data['request']) && $this->data['request'] == 'edit'){
            if($this->data['id']){
                $detail = Db::name('price_discount')->where('id',$this->data['id'])->find();
                // dump($detail);die;
                return json_encode(array('status'=>1,'data'=>$detail));
            }else{
                return json_encode(array('status'=>2,'msg'=>'请求数据有误'));
            }

        }else if(isset($this->data['request']) && $this->data['request'] == 'update'){
            if(isset($this->data['range']) && $this->data['range'] && isset($this->data['qty']) && $this->data['qty'] && isset($this->data['amount']) && $this->data['amount']){
                if(!isset($this->data['position_id']) && !$this->data['position_id']) return json_encode(array('status'=>2,'msg'=>'请选择授权职务'));
                if(strlen($this->data['range']) > 2 ) return json_encode(array('status'=>2,'msg'=>'<范围> 数据过大'));
                // dump($this->data);
                // 判断职务是否已存在
                $has_position_id = hasData('price_discount',['position_id'=>$this->data['position_id'],'id'=>['neq',$this->data['id']]]);
                if($has_position_id) return json_encode(array('status'=>2,'msg'=>lang('price_discount').' '.lang('already_exists')));

                $updateData['position_id'] = $this->data['position_id'];
                $updateData['range'] = $this->data['range'];
                $updateData['qty'] = $this->data['qty'];
                $updateData['amount'] = $this->data['amount'];
                $updateData['update_id'] = $this->user_id;
                $updateData['update_at'] = time();
                // dump($updateData);die;
                $res = updateData('price_discount',['id'=>$this->data['id']],$updateData);
                if($res){
                    return json_encode(array('status'=>1,'msg'=>lang('edited_successfully')));
                }else{
                    return json_encode(array('status'=>0,'msg'=>lang('edit_failed')));
                } 
            }else{
                return json_encode(array('status'=>2,'msg'=>lang('improve_submission_data')));
            }
        }else{
            return view('positionprice',['requestType'=>'edit','title'=>'职务价格折扣编辑','id'=>$this->data['id']]);
        }
    }

    //  部门只列出NT巴西+市场部以下的相关部门
    function getDepartment()
    {
        $department = $this->getDepartments();
        // dump( $department);die();
        return json_encode($department);
    }

    function getDepartments()
    {
        $department = getTreeChild(false,'department','country_id=1',$this->lang,5);    // 5=市场部
        $aa = Db::name('department')->where('id',5)->find();    
        $aa['langname'] = Db::name('multi_lang')->where(['mkey'=>$aa['mkey'],'lang'=>$this->lang])->value('content');
        array_unshift($department, $aa);
        $department = getTree($department,2,1);
        $bb = Db::name('department')->where('id',2)->find();       // 2=NT巴西
        $bb['langname'] = Db::name('multi_lang')->where(['mkey'=>$bb['mkey'],'lang'=>$this->lang])->value('content');
        $bb['level'] = 0;
        array_unshift($department, $bb);
        return $department;
    }


    // 职务列表列出市场总监以下的所有职务
    function getPosition()
    {
        // 职务信息22
        $position = $this->getPositions();
        // dump($position);
        return json_encode($position);
    }

    function getPositions()
    {
        $position = getTreeChild(false,'position','1=1',$this->lang,5); // 5 = 市场总监Id
        $aa = Db::name('position')->where('id',5)->find();
        $aa['langname'] = Db::name('multi_lang')->where(['mkey'=>$aa['mkey'],'lang'=>$this->lang])->value('content');
        array_unshift($position, $aa);
        $bb = Db::name('position')->where('id',3)->find();  // 3=巴西总经理Id
        $bb['langname'] = Db::name('multi_lang')->where(['mkey'=>$bb['mkey'],'lang'=>$this->lang])->value('content');
        array_unshift($position, $bb);
        $position = getTree($position,0);
        return $position;
    }


    public function cateTypes()
    {
        $join = [
            ['multi_lang mu', 'zu.mkey = mu.mkey']
        ];
        $cateTypes = getSearch('procat','zu',['zu.*,mu.content'],['mu.lang'=>$this->lang],$join,'zu.drank asc,zu.id desc');
        $cateTypes = getTree($cateTypes);

        foreach ($cateTypes as $k => $v) {
            switch ($v['level']) {
                case '1':
                    $cateTypes[$k]['content'] = '&emsp;'.$v['content'];
                    break;

                case '2':
                    $cateTypes[$k]['content'] = '&emsp;&emsp;'.$v['content'];
                    break;

                case '3':
                    $cateTypes[$k]['content'] = '&emsp;&emsp;&emsp;'.$v['content'];
                    break;

                case '4':
                    $cateTypes[$k]['content'] = '&emsp;&emsp;&emsp;&emsp;'.$v['content'];
                    break;

                case '5':
                    $cateTypes[$k]['content'] = '&emsp;&emsp;&emsp;&emsp;&emsp;'.$v['content'];
                    break;
            }
        }
        return json_encode($cateTypes);
    }

    // 價格分類刪除
    public function typeDeleteData()
    {   
        if($this->data['id']){
            $res = deleteData('price_type',['id'=>$this->data['id']]);
            if($res){
                return json_encode(array('status'=>1,'msg'=>' 价格分类名称：'.$this->data['name'].' '.lang('cleared_successfully')));
            }else{
                return json_encode(array('status'=>0,'msg'=>' 价格分类名称：'.$this->data['name'].' '.lang('clear_failed')));
            }
        }else{
            return json_encode(array('status'=>2,'msg'=>lang('improve_submission_data')));
        }
    }


    // 业务员折扣删除
    public function positionPriceDel()
    {   
        if($this->data['id']){
            $res = deleteData('price_discount',['id'=>$this->data['id']]);
            if($res){
                return json_encode(array('status'=>1,'msg'=>' 编号：'.$this->data['id'].' '.lang('cleared_successfully')));
            }else{
                return json_encode(array('status'=>0,'msg'=>' 编号：'.$this->data['id'].' '.lang('clear_failed')));
            }
        }else{
            return json_encode(array('status'=>2,'msg'=>lang('improve_submission_data')));
        }
    }

    // 定价保存
    public function priceAdd()
    {
        if(!empty($this->data['data'])){
            // dump($this->data['data']);die;
            foreach ($this->data['data'] as $k => $v) {
                // 判断24小时之内是否已存在数据， 存在则编辑数据
                $priceId = Db::name('price')->where(['pro_id'=>$v['pro_id'],'prochar_id'=>$v['prochar_id'],'create_at'=>['gt',strtotime(date("Y-m-d"))]])->order('create_at desc')->limit(1)->value('id');
                if(!$priceId){
                    $insertPriceData['pro_id'] = $v['pro_id'];
                    $insertPriceData['prochar_id'] = $v['prochar_id'];
                    $insertPriceData['create_id'] = $this->user_id;
                    $insertPriceData['create_at'] = time();
                    // 开启事务
                    // Db::startTrans();
                    $priceInsertId = insertData('price',$insertPriceData);
                    // dump($priceInsertId);die
                    $res = 0;
                    if($priceInsertId){
                        foreach ($v['price_value'] as $k1 => $v1) {
                            $insertPriceResultlData['price_id'] = $priceInsertId;
                            $insertPriceResultlData['amount'] = $v1['amount'];
                            $insertPriceResultlData['discount_range'] = $v1['discount_range'];
                            $insertPriceResultlData['moq'] = $v1['moq'];
                            $insertPriceResultlData['price_type_id'] = $v1['price_type_id'];
                            $res = insertData('price_value',$insertPriceResultlData);
                            // dump($res);
                            if(!$res){
                                Db::rollback();
                                return json_encode( array('status'=>2,'msg'=>'定价 '.lang('save').lang('failed')));
                            }
                        }
                    // }
                    }else{
                        Db::rollback();
                        return json_encode( array('status'=>0,'msg'=>'定价 '.lang('save').lang('failed')));
                    }
                }else{

                    $updateData['update_id'] = $this->user_id;
                    $updateData['update_at'] = time();
                    // 开启事务
                    // Db::startTrans();
                    $update_id = updateData('price',['id'=>$priceId],$updateData);
                    // dump($priceInsertId);die
                    $res = 0;
                    if($update_id){
                        foreach ($v['price_value'] as $k1 => $v1) {
                            $updatePriceResultlData['amount'] = $v1['amount'];
                            $updatePriceResultlData['discount_range'] = $v1['discount_range'];
                            $updatePriceResultlData['moq'] = $v1['moq'];
                            $res = updateData('price_value',['price_id'=>$priceId,'price_type_id'=>$v1['price_type_id']],$updatePriceResultlData);
                            // dump($res);
                            if($res < 0){
                                Db::rollback();
                                return json_encode( array('status'=>0,'msg'=>'定价 '.lang('save').lang('failed')));
                            }
                        }
                    // }
                    }else{
                        Db::rollback();
                        return json_encode( array('status'=>0,'msg'=>'定价 '.lang('save').lang('failed')));
                    }
                }
            }
            if($res >=0){
                Db::commit();   
                return json_encode( array('status'=>1,'msg'=>'定价 '.lang('save').lang('successfully')));
            }
                // else{
            //     Db::rollback();
            //     return json_encode( array('status'=>0,'msg'=>'定价'.'->'.lang('add_failed')));
            // }
        }else{
            return json_encode(array('status'=>2,'msg'=>lang('improve_submission_data')));
        }
    }


}